﻿using System;
using System.Collections.Generic;
using System.Linq;
using Common;
using DAL;
using HtmlAgilityPack;
using HtmlHelper;
using Models;
using Models.SqlitModel;

namespace BLL
{
    public class BooksBLL
    {
        private BooksDAL booksDAL;
        private BooksChapterDAL chapterDAL;
        public BooksBLL()
        {
            booksDAL = new BooksDAL();
            chapterDAL = new BooksChapterDAL();
        }
        public List<Books> QueryBooks(ref DataPage page, string name = "", string url = "")
        {
            return booksDAL.QueryBooks(ref page, name, url);
        }
        /// <summary>
        /// 获取进度
        /// </summary>
        /// <returns></returns>
        public List<int> QueryProgress()
        {
            return booksDAL.QueryProgress();
        }
        /// <summary>
        /// 查询未获取章节的小说
        /// </summary>
        /// <returns></returns>
        public Books QueryBook()
        {
            return booksDAL.QueryBook();
        }
        /// <summary>
        /// 获取小说列表
        /// </summary>
        /// <param name="url"></param>
        public void GetBooksFromHttp(string url)
        {
            var html = ParserHtml.LoadHtml(url);
            var list = GetAllFiction(html);
            var nameList = list.Select(o => o.Text).ToList();
            var have = booksDAL.QueryBooks(nameList);
            List<Books> books = new List<Books>();
            foreach (var iteMenuse in list)
            {
                if (!have.FindAll(o => o.Name == iteMenuse.Text && o.Href == iteMenuse.Href).Any())
                {
                    var xs = new Books()
                    {
                        Id = Guid.NewGuid().ToString(),
                        Name = iteMenuse.Text,
                        Href = iteMenuse.Href,
                        State = "未下载",
                        AddTime = DateTime.Now
                    };
                    books.Add(xs);
                }
            }
            if (books.Any())
            {
                booksDAL.InsertBook(books);
            }
        }

        /// <summary>
        /// 获取页面中的所有小说
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public List<Menus> GetAllFiction(HtmlDocument doc)
        {
            var arrayList = new List<Menus>();
            try
            {
                HtmlNodeCollection hrefs = doc.SelectNode("//li/a[@href]");
                if (hrefs == null)
                    return null;
                foreach (HtmlAgilityPack.HtmlNode href in hrefs)
                {
                    string text = HtmlHelper.HtmlNode.InnerText(href);
                    string hreff = HtmlHelper.HtmlNode.GetNodeAttribute(href, "href").Value;
                    arrayList.Add(new Menus() { Text = text, Href = hreff });
                }
            }
            catch (Exception)
            {
                // ignored
            }
            return arrayList.ToArray().ToList();
        }
        /// <summary>
        /// 获取章节目录
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public List<Menus> GetMenu(HtmlDocument doc)
        {
            var arrayList = new List<Menus>();
            try
            {
                HtmlNodeCollection hrefs = doc.SelectNode("//dd/a[@href]");
                if (hrefs == null)
                    return null;
                foreach (HtmlAgilityPack.HtmlNode href in hrefs)
                {
                    string text = HtmlHelper.HtmlNode.InnerText(href);
                    string hreff = HtmlHelper.HtmlNode.GetNodeAttribute(href, "href").Value;
                    arrayList.Add(new Menus() { Id = Helper.ConvertTitle(text), Text = text, Href = hreff });
                }
            }
            catch (Exception)
            {
                // ignored
            }
            return arrayList.Distinct().OrderByDescending(o => o.Id).ToList();
        }


        /// <summary>
        /// 获取小说章节目录
        /// </summary>
        public bool GetChapterList(Books book)
        {
            try
            {
                var html = ParserHtml.LoadHtml(book.Href);
                var list = GetMenu(html) ?? new List<Menus>();
                var bclist = new List<BooksChapter>();
                foreach (var item in list)
                {
                    BooksChapter bc = new BooksChapter()
                    {
                        Id = Guid.NewGuid().ToString(),
                        Name = item.Text,
                        Href = item.Href,
                        State = "未下载",
                        AddTime = DateTime.Now,
                        Code = item.Id,
                        XsId = book.Id
                    };
                    bclist.Add(bc);
                }
                if (bclist.Any())
                {
                    chapterDAL.InsertBooksChapter(bclist);
                }
                book.State = "已下载";
                booksDAL.UpdateBook(book);
                return true;
            }
            catch (Exception e)
            {
                book.State = "下载失败";
                booksDAL.UpdateBook(book);
                return false;
            }
        }
    }
    /// <summary>
    /// 目录信息
    /// </summary>
    public class Menus
    {
        /// <summary>
        /// 章节编号
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// 目录文本
        /// </summary>
        public string Text { get; set; }
        /// <summary>
        /// 目录链接
        /// </summary>
        public string Href { get; set; }
    }
}
